package com.yxkj.syh.app.huarong.activities.orders.received;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.lcw.library.imagepicker.ImagePicker;
import com.syh.app.basic.base.BaseActivity;
import com.syh.app.basic.bean.LiveDataEvent;
import com.syh.app.basic.config.BasicConstants;
import com.syh.app.basic.utils.AppUtil;
import com.syh.app.basic.utils.ComUtil;
import com.syh.app.basic.utils.Loog;
import com.syh.app.basic.utils.PermissionUtil;
import com.syh.app.basic.utils.Tooast;
import com.syh.app.basic.utils.imagepickerhelper.ImagePickerHelper;
import com.syh.app.basic.views.ImageWatcher;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yxkj.syh.app.huarong.BR;
import com.yxkj.syh.app.huarong.R;
import com.yxkj.syh.app.huarong.adps.GoodsCheckAdp;
import com.yxkj.syh.app.huarong.bean.CheckInfo;
import com.yxkj.syh.app.huarong.bean.Goods;
import com.yxkj.syh.app.huarong.bean.OrderInfo;
import com.yxkj.syh.app.huarong.bean.ReceiveRequest;
import com.yxkj.syh.app.huarong.constants.ArouterPath;
import com.yxkj.syh.app.huarong.databinding.ActivityReceiveBinding;
import com.yxkj.syh.app.huarong.util.PhotoUtil;
import com.yxkj.syh.app.huarong.views.ReceiveGoodsCheckDialog;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 收货 确认收货
 */
@Route(path = ArouterPath.RECEIVE_ACTIVITY)
public class ReceiveActivity extends BaseActivity<ActivityReceiveBinding, ReceiveVM> {
    public static final int PERMISSION_IMAGE = 0xb12;
    private static final int TYPE_HZD = 0;//回执单
    private static final int TYPE_PZ = 1;//凭证

    @Autowired
    long orderID;

    private GoodsCheckAdp mGoodsCheckAdp;
    private ReceiveGoodsCheckDialog mReceiveGoodsCheckDialog;
    private String hzdUrl;
    private List<String> pzUrlList = new ArrayList<>();

    @Override
    protected int getContentLayout() {
        return R.layout.activity_receive;
    }

    @Override
    protected int getViewModelId() {
        return BR.receiveVM;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {

        mVDBinding.titleView.setLeftOnClickListener(v -> finish());

        mVDBinding.pllContent.showLoading();


        mVDBinding.ivRemoveHzd.setOnClickListener(v -> {
            mVDBinding.ivRemoveHzd.setVisibility(View.GONE);
            mVDBinding.ivEditHzd.setImageResource(R.mipmap.ic_add_image);
            hzdUrl = null;
        });

        mGoodsCheckAdp = new GoodsCheckAdp();
        mVDBinding.rvGoods.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        mVDBinding.rvGoods.setAdapter(mGoodsCheckAdp);
        mGoodsCheckAdp.setOnClick(goods -> {

            //验货数量对话框
            if (mReceiveGoodsCheckDialog == null) {
                mReceiveGoodsCheckDialog = new ReceiveGoodsCheckDialog(ReceiveActivity.this);
                mReceiveGoodsCheckDialog.setOnConfirmClickListener(new ReceiveGoodsCheckDialog.OnConfirmClickListener() {
                    @Override
                    public void onConfirm(Goods goods1) {
                        mGoodsCheckAdp.change(goods1);
                    }

                    @Override
                    public void onSelectGoods() {
                        if (mViewModel.mldGoods.getValue() == null) {
                            mViewModel.goodsList();
                        } else {
                            selectGoods(mViewModel.mldGoods.getValue());
                        }
                    }
                });
            }
            mReceiveGoodsCheckDialog.build(goods);
            mReceiveGoodsCheckDialog.show();
        });

        mVDBinding.btnConfirm.setOnClickListener(v -> {

            if (TextUtils.isEmpty(hzdUrl)) {
                Tooast.normalInfo("请上传回执单");
            } else {
                mViewModel.editGoods(mGoodsCheckAdp.getData());
            }

        });

        mVDBinding.ivAddPz.setOnClickListener(v -> uploadImage(TYPE_PZ));

        mVDBinding.ivEditHzd.setOnClickListener(v -> {
            if (!TextUtils.isEmpty(hzdUrl)) {
                new ImageWatcher(ReceiveActivity.this).show(hzdUrl);
            } else {
                uploadImage(TYPE_HZD);
            }
        });
    }

    @Override
    protected void initData() {
        mViewModel.getOrderDetail(orderID);
    }

    @Override
    protected void initObservers() {
        super.initObservers();
        mViewModel.mldImageUrl.observe(this, s -> {
            switch (mCurrentOperateType) {
                case TYPE_HZD://上传回执单
                    hzdUrl = s;
                    Glide.with(ReceiveActivity.this).load(s).apply(RequestOptions.errorOf(R.mipmap.ic_add_image).diskCacheStrategy(DiskCacheStrategy.NONE)).into(mVDBinding.ivEditHzd);
                    mVDBinding.ivRemoveHzd.setVisibility(View.VISIBLE);
                    break;
                case TYPE_PZ://上传凭证

                    addPzView(s);

                    break;
            }
        });
        mViewModel.mldOrderDetail.observe(this, orderDetail -> {
            OrderInfo orderInfo = orderDetail.getOrderInfo();
            if (orderInfo.getFlag() == 0) {
                for (Goods goods : orderInfo.getDetails()) {
                    goods.setSettleQuantity(null);//手动置空  为了判断有没有输入实际验收数量
                }
            } else if (orderInfo.getFlag() == 1) {

                CheckInfo checkInfo = mViewModel.getCheckInfo();

                //回执单
                Glide.with(ReceiveActivity.this).load(checkInfo.getReceipt()).apply(RequestOptions.errorOf(R.mipmap.ic_add_image).diskCacheStrategy(DiskCacheStrategy.NONE)).into(mVDBinding.ivEditHzd);
                mVDBinding.ivRemoveHzd.setVisibility(View.VISIBLE);
                hzdUrl = checkInfo.getReceipt();

                mViewModel.ofRemark.set(mViewModel.getLogMsg(2, 1));

                if (checkInfo.getCertificates() != null) {
                    //凭证
                    int size = checkInfo.getCertificates().size() > 6 ? 6 : checkInfo.getCertificates().size();
                    for (int i = 0; i < size; i++) {
                        addPzView(checkInfo.getCertificates().get(i));
                    }
                }

            }
            mGoodsCheckAdp.setNewData(orderDetail.getOrderInfo().getDetails());
            if (mVDBinding.pllContent.isLoadingCurrentState()) {
                mVDBinding.pllContent.showContent();
            }
        });

        mViewModel.mldEditGoods.observe(this, aBoolean -> {
            ReceiveRequest request = new ReceiveRequest();
            request.setId(orderID);
            request.setMessage(mViewModel.ofRemark.get());
            ReceiveRequest.Params params = new ReceiveRequest.Params();
            request.setParams(params);
            params.setType(mVDBinding.rbYes.isChecked() ? 1 : 0);
            params.setReceipt(hzdUrl);

            //水分
            if (TextUtils.isEmpty(mViewModel.ofForm1.get())) {
                params.setWaterQuantity(BigDecimal.ZERO);
            } else {
                params.setWaterQuantity(new BigDecimal(mViewModel.ofForm1.get()));
            }
            //杂纸
            if (TextUtils.isEmpty(mViewModel.ofForm2.get())) {
                params.setImpurityQuantity(BigDecimal.ZERO);
            } else {
                params.setImpurityQuantity(new BigDecimal(mViewModel.ofForm2.get()));
            }
            //杂质
            if (TextUtils.isEmpty(mViewModel.ofForm3.get())) {
                params.setDiscardQuantity(BigDecimal.ZERO);
            } else {
                params.setDiscardQuantity(new BigDecimal(mViewModel.ofForm3.get()));
            }
            //其他
            if (TextUtils.isEmpty(mViewModel.ofForm4.get())) {
                params.setOtherQuantity(BigDecimal.ZERO);
            } else {
                params.setOtherQuantity(new BigDecimal(mViewModel.ofForm4.get()));
            }

            params.setDeduct(0);
            params.setDeductQuantity(BigDecimal.ZERO);
            params.setCertificates(pzUrlList);
            mViewModel.receive(request);
        });

        mViewModel.mldReceive.observe(this, aBoolean -> {
            if (aBoolean) {
                EventBus.getDefault().post(new LiveDataEvent(BasicConstants.EVENT_SELECT_ORDER_ALL));
                setResult(RESULT_OK);
                finish();
            }
        });

        mViewModel.mldGoods.observe(this, goodsList -> {
            selectGoods(goodsList);
        });
    }


    /**
     * 添加凭证图片
     *
     * @param url
     */
    private void addPzView(String url) {
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ComUtil.Dp2Px(this, 90), ComUtil.Dp2Px(this, 90));
        layoutParams.rightMargin = ComUtil.Dp2Px(this, 10);

        pzUrlList.add(url);
        FrameLayout pzLayout = (FrameLayout) LayoutInflater.from(this).inflate(R.layout.activity_receive_pz, null);
        ImageView ivEditPz = pzLayout.findViewById(R.id.ivEditPz);
        ImageView ivRemovePz = pzLayout.findViewById(R.id.ivRemovePz);
        Glide.with(ReceiveActivity.this).load(url).apply(RequestOptions.errorOf(R.mipmap.ic_add_image).diskCacheStrategy(DiskCacheStrategy.NONE)).into(ivEditPz);
        ivEditPz.setTag(url);
        ivRemovePz.setTag(url);
        ivEditPz.setOnClickListener(v -> {
            new ImageWatcher(ReceiveActivity.this).show((String) v.getTag());
        });
        ivRemovePz.setOnClickListener(v -> {
            pzUrlList.remove(v.getTag());
            mVDBinding.llPz.removeView(pzLayout);
            mVDBinding.llPz.requestLayout();
            setAddPzVisibility();
        });

        setAddPzVisibility();

        mVDBinding.llPz.addView(pzLayout, layoutParams);
        pzLayout.requestLayout();
    }

    private void setAddPzVisibility() {
        if (pzUrlList.size() < 6) {
            mVDBinding.ivAddPz.setVisibility(View.VISIBLE);
        } else {
            mVDBinding.ivAddPz.setVisibility(View.GONE);
        }
    }

    private int mCurrentOperateType = TYPE_HZD;

    private void uploadImage(int type) {
        mCurrentOperateType = type;
        AndPermission.with(ReceiveActivity.this).requestCode(PERMISSION_IMAGE)
                .permission(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .callback(mPermissionListener).start();
    }

    private void selectGoods(List<Goods> goodsList) {
        String[] items = new String[goodsList.size()];
        for (int i = 0; i < goodsList.size(); i++) {
            Goods goods = goodsList.get(i);
            items[i] = goods.getName();
        }
        new AlertDialog.Builder(this).setItems(items, (dialog, which) -> {
            mReceiveGoodsCheckDialog.setNewGoods(goodsList.get(which));
        }).create().show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == ImagePickerHelper.REQUEST_SELECT_IMAGES_CODE) {
                List<String> imagePaths = data.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES);
                Loog.d("ReceiveActivity", "imagePaths = " + imagePaths);
                Luban.with(this).load(imagePaths.get(0))
                        .setTargetDir(AppUtil.getLubanPath())
                        .ignoreBy(100)
                        .setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {
                                showLoading("Compress");
                            }

                            @Override
                            public void onSuccess(File file) {
                                hideLoading("Compress");
                                Loog.d("ReceiveActivity", "file.length() = " + file.length());
                                mViewModel.uploadImage(file);
                            }

                            @Override
                            public void onError(Throwable e) {
                                hideLoading("Compress");
                                Tooast.normalInfo("压缩图片错误");

                            }
                        }).launch();
            } else if (requestCode == PhotoUtil.GET_IMAGE_BY_CAMERA) {
                File imageFile;
                if (Build.VERSION.SDK_INT >= 19) {
                    imageFile = ComUtil.getUriFromKitKat(this, PhotoUtil.imageUriFromCamera);
                } else {
                    imageFile = ComUtil.getUriBeforeKitKat(this, PhotoUtil.imageUriFromCamera);
                }
                Loog.d("ReceiveActivity", "imageFile.length() = " + imageFile.length());
                if (imageFile.length() > 1 * 1024 * 1024) {
                    Luban.with(this).load(imageFile)
                            .setTargetDir(AppUtil.getLubanPath())
                            .ignoreBy(100)
                            .setCompressListener(new OnCompressListener() {
                                @Override
                                public void onStart() {
                                    showLoading("Compress");
                                }

                                @Override
                                public void onSuccess(File file) {
                                    hideLoading("Compress");
                                    Loog.d("ReceiveActivity", "file.length() = " + file.length());
                                    mViewModel.uploadImage(file);
                                }

                                @Override
                                public void onError(Throwable e) {
                                    hideLoading("Compress");
                                    Tooast.normalInfo("压缩图片错误");

                                }
                            }).launch();
                } else {
                    mViewModel.uploadImage(imageFile);
                }
            }
        }
    }

    private void startImageLib() {
        ImagePickerHelper.startImagePicker(this);
    }

    private PermissionListener mPermissionListener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            if (requestCode == PERMISSION_IMAGE) {
                new AlertDialog.Builder(ReceiveActivity.this).setItems(new String[]{"相册", "拍照"}, (dialog, which) -> {
                            dialog.cancel();
                            if (which == 0) {
                                startImageLib();
                            } else if (which == 1) {
                                PhotoUtil.openCameraImage(ReceiveActivity.this);
                            }
                        }
                ).create().show();
            }
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            if (requestCode == PERMISSION_IMAGE) {
                PermissionUtil.with(ReceiveActivity.this)
                        .addPermission(Manifest.permission.CAMERA)
                        .addPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                        .addPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .initPermission();
            }
        }
    };

}
